package com.anbang.app.ui.frame.activity

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.util.Log
import android.widget.Toast
import com.airbnb.lottie.LottieAnimationView
import com.anbang.app.R
import com.anbang.app.base.activity.BaseActivity
import com.anbang.app.ui.frame.fragment.MineFragment
import com.anbang.app.ui.frame.fragment.OneTabFragment
import com.anbang.app.ui.frame.fragment.ThreeTabFragment
import com.anbang.app.ui.frame.fragment.TwoTabFragment
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : BaseActivity() {
    

    //地标菜单View
    lateinit var animViews: Set<LottieAnimationView>

    //当前展示Fragment 存储
    lateinit var nowShowFragment: Fragment

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val fragments:List<Fragment> = arrayListOf(OneTabFragment(),TwoTabFragment(),ThreeTabFragment(),MineFragment())

        //默认展示首页Fragment
        supportFragmentManager.beginTransaction().add(R.id.fragmentLayout,fragments[0]).commit()
        nowShowFragment=fragments[0]
        homeLottie.progress=1f

        animViews = setOf(homeLottie, categoryLottie, discoverLottie, userLottie)

        //首页点击
        homeLottie.setOnClickListener { resetNavigation(homeLottie,fragments[0]) }

        //分类点击
        categoryLottie.setOnClickListener { resetNavigation(categoryLottie,fragments[1]) }

        //发现点击
        discoverLottie.setOnClickListener { resetNavigation(discoverLottie,fragments[2]) }

        //我的点击
        userLottie.setOnClickListener { resetNavigation( userLottie,fragments[3]) }
    }

    /**
     * 点击切换底部tab动画
     */
    private fun resetNavigation( nowView: LottieAnimationView,fragment: Fragment) {
       Log.d("=",""+nowView.progress)
        if (nowView.progress==0.0f){ //跳转到制定Fragment
            nowView.playAnimation()
            animViews.forEach {
                if (it != nowView) {
                    it.cancelAnimation()
                    it.progress = 0f
                }
            }
            resetFragment(fragment)
        }else{//已在当前Fragment 刷新
            Toast.makeText(this@MainActivity,"刷新", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 切换Fragment
     */
    private  fun resetFragment(fragment: Fragment){
        val fragmentTransaction = supportFragmentManager.beginTransaction()

        when {
            //Fragment 已被添加过
            fragment.isAdded ->fragmentTransaction.hide(nowShowFragment).show(fragment).commit()
            //Fragment 未被添加
            else -> fragmentTransaction.hide(nowShowFragment).add(R.id.fragmentLayout,fragment).commit()
        }
        nowShowFragment=fragment
    }

    /**
     * 点击返回键 不移出回退栈
     */
    override fun onBackPressed() {
        moveTaskToBack(false)
    }
}
